from selenium import webdriver
import time
import xlrd

class Login_test():
    def __init__(self):
        self.dr = webdriver.Chrome()     #实例化浏览器对象

    # 打开WoniuSales并登录
    def login(self,username,password,verifycode):
        self.dr.get("http://192.168.2.159:8080/woniusales/")        #发送访问woniusales的请求
        self.dr.find_element_by_id('username').clear()        # 清空用户名
        self.dr.find_element_by_id('username').send_keys(username)     # 输入用户名
        self.dr.find_element_by_id('password').clear()     # 清空密码
        self.dr.find_element_by_id('password').send_keys(password)    # 输入密码
        self.dr.find_element_by_id("verifycode").clear()    #清空验证码
        self.dr.find_element_by_id("verifycode").send_keys(verifycode)      #输入验证码
        self.dr.find_element_by_xpath("//div[4]/div/form/div[6]/button").click()      #点击登录

    # 验证登录结果
    def login_verify(self,username,password,verifycode,expect):
        self.login(username,password,verifycode)       #登录
        time.sleep(2)
        try:
            actural = self.dr.find_element_by_class_name("bootbox-body").text        #获取登录后提示语
            print(actural)
            if expect in actural:      #断言登录结果是否正确
                print("succeed")
            else:
                print("failed")
        except:
            print("login succeed.")
            self.dr.find_element_by_xpath('//*[@id="navbar"]/ul[2]/li[2]/a').click()    #点击注销

    # 实现txt数据驱动
    def txt_driver(self):
        with open("data.txt") as f:  # 取文件里每一组用户名、密码、验证码、提示语
            content = f.readlines()
            print(content)
        for line in content:
            username = line.strip().split(',')[0]
            password = line.strip().split(',')[1]
            verifycode = line.strip().split(',')[2]
            expect = line.strip().split(',')[3]
            self.login_verify(username,password,verifycode,expect)

    # 实现excel数据驱动
    def excel_driver(self):
        with open("data01.xls") as f:
            work_b=xlrd.open_workbook("data01.xls")
            work_sh = work_b.sheets()
            sheet_one = work_sh[0]
            for i in range(1,sheet_one.nrows):
                username = sheet_one.cell(i,0).value
                password = sheet_one.cell(i,1).value
                verifycode = sheet_one.cell(i,2).value
                # print(type(verifycode))
                expect = sheet_one.cell(i,3).value
                self.login_verify(username, password, verifycode, expect)

    # 关闭所有窗口
    def quit_driver(self):
        self.dr.quit()


if __name__ == '__main__':
    t = Login_test()
    # t.excel_driver()
    t.txt_driver()
    t.quit_driver()




